<?php

class Admin_Table_Auction_ParcelAuction extends Apk_Db_Table {

    protected $_name = 'parcel_auction';
    protected $_primary = 'id';
    public $_ERROR = "";

    public function __construct($config){
    	try {
        	$options = $config->database2->toArray();
        	$dbType = $config->database2->type;
        	unset($options['type']);
        	unset($options['profiler_enabled']);

            $db = Zend_Db::factory($dbType, $options);
            Zend_Registry::set( 'db2', $db );
		    $db->getConnection();
		} catch ( Zend_Db_Adapter_Exception $e ) {
		    	echo $e->getMessage();
		} catch ( Zend_Exception $e ) {
		    	echo $e->getMessage();
		}
    }
    
    public function GetError() {
        return $this->_ERROR;
    }

    private function dataPreparation($dataIn, $dataOut = array()){
    	if (is_array($dataIn) && !empty($dataIn)){
    		foreach ($dataIn as $key=>$val) {
	    		switch ($key) {
	    			case 'the_geom':
	    				if(is_array($val)){
	    					$PPoint = "";
	    				}else $PPoint = $val;
	    				if(trim($PPoint)!="") $dataOut[$key]=new Zend_Db_Expr("ST_GeomFromText('MULTIPOLYGON(((".$PPoint.")))',-1)");
	    				break;
		    		case 'cad_num':
		    			$dataOut['cadnum']=$val;
		    			list($dataOut['cad_num_koatuu'],$dataOut['cad_num_zone'],$dataOut['cad_num_quarter'],$dataOut['cad_num_parcel']) = explode(':',$val);
		    			break;
		    		case 'parcel_address':
		    			$dataOut['address']=$val;
		    			break;
		    		case 'start_price':
		    			$dataOut['normative']=$val;
		    			break;
		    		case 'id_status':
		    			$dataOut['lot_status']=$val;
		    			break;
		    		case 'purpose':
		    		case 'area':
	    			case 'id_lot':
		    		case 'id_auction':
		    		case 'id_exchange':
		    		case 'coordsys_code':
		    		case 'area_measurement':
		    		case 'ownership_code':
		    		case 'use':
		    		case 'category':
		    			$dataOut[$key]=$val;
		    			break;
		    		
		    	}
    		}
    	}
    	return $dataOut;
    }
    
    public function insert(array $data) {
    	$data = $this->dataPreparation($data);
    	
        try {
            Zend_Registry::get('db2')->insert($this->_name, $data);
            return Zend_Registry::get('db2')->lastInsertId($this->_name);
        } catch (Exception $e) {
            $this->_ERROR = $e->getMessage();
        }
    }
}
